import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2023-04-05
 * Time: 10:16
 */
public class TcpEchoServer {
private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
      serverSocket = new ServerSocket(port);

    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);
        }
    }
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.println("客户端上线"+clientSocket.getInetAddress().toString()+clientSocket.getPort());
       try(InputStream inputStream = clientSocket.getInputStream();
           OutputStream outputStream = clientSocket.getOutputStream();

               ){
           PrintWriter printWriter =  new PrintWriter(outputStream);
           Scanner scanner = new Scanner(inputStream);
           while (true){
               if(!scanner.hasNext()){
                   System.out.println("客户端下线"+clientSocket.getInetAddress().toString()+clientSocket.getPort());
                   break;
               }
               String request = scanner.next();
               String response = process(request);
               printWriter.println(response);
               System.out.println("请求为"+request+"响应为"+inputStream);
           }

       } catch (IOException e) {
           throw new RuntimeException(e);
       }finally {
           clientSocket.close();
       }
    }

    private String process(String request) {
      return   request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(6666);
        tcpEchoServer.start();
    }
}
